package com.lhj.springboot3.core.controller;

import com.lhj.springboot3.core.bean.UserEntity;
import com.lhj.springboot3.core.event.LoginSuccessEvent;
import com.lhj.springboot3.core.event.PublisherEvent;
import com.lhj.springboot3.core.service.IntegralService;
import com.lhj.springboot3.core.service.LoginLoggerService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @Author lhj
 * @Date 2024/6/30 10:26
 */
@RestController
public class LoginController {
    
    @Autowired
    private IntegralService integralService;
    
    @Autowired
    private LoginLoggerService loggerService;
    
    @Resource
    private PublisherEvent publisherEvent;

    /**
     * 登录接口 基于同步调用
     * @param username
     * @param password
     * @return
     */
    @PostMapping(value = "/login")
    public ResponseEntity<String> login(@RequestParam("username") String username, @RequestParam("password") String password){
        //1. 判断用户名和密码是否正确
        if (!("lhj".equals(username) && "123".equals(password))) {
            return new ResponseEntity<>("用户名或密码错误", HttpStatus.BAD_REQUEST);
        }
        //2. 赠送积分
        integralService.sendIntegral(username);
        //3. 记录登录日志
        loggerService.recordLoginLog(username);
        return new ResponseEntity<>("登录成功", HttpStatus.OK);
    }
    
    @PostMapping(value = "/event/login")
    public ResponseEntity<?> eventLogin(@RequestParam("username") String username, @RequestParam("password") String password){
        //1. 判断用户名和密码是否正确
        if (!("lhj".equals(username) && "123".equals(password))) {
            return new ResponseEntity<>("用户名或密码错误", HttpStatus.BAD_REQUEST);
        }
        //2. 赠送积分
        //发送赠送积分事件
        //3. 记录登录日志
        //记录登录日志事件
        LoginSuccessEvent event = new LoginSuccessEvent(new UserEntity(username, password));
        publisherEvent.publishEvent(event);
        return new ResponseEntity<>("登录成功", HttpStatus.OK);
    }
    
}
